package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {

@Autowired
private DeptService deptService;
@Autowired
private EmpExprService empExprService;
    @Override
    public PageResult<Emp> pageQuery(EmpQueryParam param) {
        //1. 设置分页参数(MyBatis-Plus)
        IPage<Emp> page = new Page<>(param.getPage(), param.getPageSize());
        //2. 执行查询 只有分页条件，没有查询条件
        LambdaQueryWrapper<Emp> queryWrapper=new LambdaQueryWrapper<Emp>()
                .like(param.getName() != null, Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd());
        this.page(page,queryWrapper);
        //处理部门名称展示
        List<Emp> emps = page.getRecords();
        emps.forEach(emp -> {
            Dept dept = deptService.getById(emp.getDeptId());
            if(dept != null){
                emp.setDeptName(dept.getName());
            }
        });
        //3. 封装查询结果
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    @Override
    public void saveEmp(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());

        save(emp);

        // 调用service层方法保存员工工作经历信息
        List<EmpExpr> exprList = emp.getExprList();
        // 添加工作经历所属员工
        exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        empExprService.saveBatch(exprList);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        removeBatchByIds(ids);
        empExprService.remove(
                new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids)
        );
    }
}
